package com.example.home.pet.activity;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import com.bumptech.glide.Glide;
import com.example.home.R;
import com.example.home.government.bean.ImgBean;
import com.example.home.pet.bean.CaseInquiryBean;
import com.example.home.pet.bean.DoctorListBean;
import com.example.home.tool.GeneralClass;
import com.example.home.tool.OKHttpTool;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;

import static com.example.home.tool.StaticActi.ip;

public class DoctorInquiryDetail extends AppCompatActivity {

    private DoctorListBean.RowsBean doctorListBean;
    private CaseInquiryBean.RowsBean caseInquiryBean;
    private int mode;
    private static final int PICK_IMAGE_REQUEST = 122;
    private ImageView back;
    private ImageView avatar;
    private TextView name;
    private TextView jobName;
    private TextView practiceNo;
    private EditText edImport;
    private String serviceImgUrl;
    private Button btnSend;
    private Button btn_img;
    private String filePath;
    private ImageView img;
    private Gson gson;
    private static final int REQUEST_PERMISSION_CODE = 1;
    private final static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,};



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_doctor_inquiry_detail);
        gson = new Gson();



        Intent intent = getIntent();
        String strCaseInquiryBean = intent.getStringExtra("CaseInquiryBean");
        String strDoctorListBean = intent.getStringExtra("DoctorListBean");

        if(!TextUtils.isEmpty(strCaseInquiryBean)){
            mode=1;
            caseInquiryBean = gson.fromJson(strCaseInquiryBean, CaseInquiryBean.RowsBean.class);
        }else if(!TextUtils.isEmpty(strDoctorListBean)){
            mode=2;
            doctorListBean = gson.fromJson(strDoctorListBean, DoctorListBean.RowsBean.class);
        }

        verifyStoragePermissions(this);
        initView();
        //提交请求
        sendProblem();
    }

    private void verifyStoragePermissions(DoctorInquiryDetail doctorInquiryDetail) {
        try {
            //判断当前系统是否是Android6.0(对应API 23)以及以上，如果是则判断是否含有了权限
            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
                //检测是否有写的权限
                int permission = ActivityCompat.checkSelfPermission(this,
                        "android.permission.WRITE_EXTERNAL_STORAGE");
                /***
                 * checkSelfPermission返回两个值
                 * 有权限: PackageManager.PERMISSION_GRANTED
                 * 无权限: PackageManager.PERMISSION_DENIED
                 */
                if (permission != PackageManager.PERMISSION_GRANTED) {
                    // 没有写的权限，去申请写的权限，会弹出对话框
                    ActivityCompat.requestPermissions(this, PERMISSIONS_STORAGE, REQUEST_PERMISSION_CODE);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //回调函数，申请权限后回调onRequestPermissionResult函数，第一个参数为请求码，第二个参数是刚刚请求的权限集，第三个参数是请求结果，0表示授权成功，-1表示授权失败
    //requestCode：这个对应请求状态码，permissions：这个是前面你要申请的权限集合，grantResults：这个是申请权限的结果
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_PERMISSION_CODE) {
            for (int i = 0; i < permissions.length; i++) {
                //grantResults[i]：返回0，表示授权成功，返回-1，表示授权失败
                Log.i("111333", "申请的权限为：" + permissions[i] + ",申请结果：" + grantResults[i]);
            }
        }
    }

    private void sendProblem() {
        int id = 0;
        if (caseInquiryBean != null) {
            id = caseInquiryBean.getId();
        } else if (mode == 2) {
            id = doctorListBean.getId();
        }
        String question = edImport.getText().toString();
        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("doctorId",id);
            jsonObject.put("question",question);
            jsonObject.put("imageUrls",serviceImgUrl);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        if (question != null){
            btnSend.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    OKHttpTool.doNetRequest("prod-api/api/pet-hospital/inquiry",
                            OKHttpTool.POST,
                            GeneralClass.class,
                            new OKHttpTool.NetCallback() {
                                @Override
                                public void onSuccess(Object obj) {
                                    GeneralClass generalClass = (GeneralClass) obj;
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            if (generalClass.getCode() == 200){
                                                Toast.makeText(DoctorInquiryDetail.this,"提交成功",Toast.LENGTH_SHORT).show();
                                                DoctorInquiryDetail.this.finish();
                                            }else {
                                                Toast.makeText(DoctorInquiryDetail.this,"提交失败",Toast.LENGTH_SHORT).show();
                                            }
                                        }
                                    });
                                }

                                @Override
                                public void onFailure(String msg) {

                                }
                            },jsonObject.toString());
                }
            });
        }
    }

    private void initView() {
        back = findViewById(R.id.back);
        avatar = findViewById(R.id.avatar);
        practiceNo = findViewById(R.id.practiceNo);
        edImport = findViewById(R.id.ed_import);
        btnSend = findViewById(R.id.btn_send);
        btn_img = findViewById(R.id.btn_img);
        img = findViewById(R.id.img);
        jobName = findViewById(R.id.jobName);
        name = findViewById(R.id.name);

        if(mode==1){
            Glide.with(DoctorInquiryDetail.this).load(ip+caseInquiryBean.getDoctor().getAvatar()).into(avatar);
            name.setText(caseInquiryBean.getDoctor().getName());
            jobName.setText("职务："+caseInquiryBean.getDoctor().getJobName());
            practiceNo.setText("执业编号："+caseInquiryBean.getDoctor().getPracticeNo());
        }else if(mode==2){
            Glide.with(DoctorInquiryDetail.this).load(ip+doctorListBean.getAvatar()).into(avatar);
            name.setText(doctorListBean.getName());
            jobName.setText("职务："+doctorListBean.getJobName());
            practiceNo.setText("执业编号："+doctorListBean.getPracticeNo());
        }


        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DoctorInquiryDetail.this.finish();
            }
        });
        btn_img.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                openGallery(v);
            }
        });

    }

    private void openGallery(View v) {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, PICK_IMAGE_REQUEST);
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null) {
            Uri selectedImageUri = data.getData();
            String imagePath = getRealPathFromUri(selectedImageUri);

            if (imagePath != null) {
                ImageView imageView = findViewById(R.id.img);
                imageView.setImageURI(selectedImageUri);
                btn_img.setVisibility(View.GONE);
                // 调用上传图片方法
                uploadImage(selectedImageUri);
            } else {
                // 处理无法获取文件路径的情况
                Toast.makeText(DoctorInquiryDetail.this, "上传图片失败", Toast.LENGTH_SHORT).show();
            }
        }
    }


    public String getRealPathFromUri(Uri uri) {
        String[] projection = {MediaStore.Images.Media.DATA};
        Cursor cursor = getContentResolver().query(uri, projection, null, null, null);
        if (cursor != null) {
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            if (cursor.moveToFirst()) {
                filePath = cursor.getString(column_index);
                cursor.close();
                return filePath;
            } else {
                cursor.close();
            }
        }
        return null;
    }


    //上传图片
    public void uploadImage(Uri imageUri) {
        String filePath = getRealPathFromUri(imageUri);
        File fileToUpload = new File(filePath);
        OKHttpTool.uploadFile(fileToUpload, ImgBean.class, new OKHttpTool.NetCallback() {
            @Override
            public void onSuccess(Object obj) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        // 上传成功后的处理逻辑
                        // obj 是服务器响应的解析结果，根据您的需求进行处理
                        serviceImgUrl = ((ImgBean) obj).getUrl();
                        Toast.makeText(DoctorInquiryDetail.this,"上传成功",Toast.LENGTH_SHORT).show();
                    }
                });
            }

            @Override
            public void onFailure(String msg) {
                // 上传失败后的处理逻辑
                // msg 包含了失败的原因，根据您的需求进行处理
                Log.e("xhf","=="+msg);
            }
        });
    }
}